<template>
  <div class="linkageConfig">
    <div class="linkage">
      <div v-if="!!isShow">
        <el-divider>数据联动</el-divider>
        <!-- {{formData}} -->
        <el-form label-width="80px" v-if="parentFieldList.length > 0" size="small" :model="formData" ref="formData">
          <div class="contentBox" v-for="(item, index) in formData.linkageList" :key="index">
            <el-form-item label="上级字段" :prop="`linkageList.${index}.parentId`" :rules="rules.parentId">
              <el-select v-model="item.parentId" @change="valueChange" class="width100">
                <el-option v-for="(fieldItem, index) in parentFieldList" :key="index" :value="fieldItem.formId" :label="fieldItem.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="item.parentId !== ''" :prop="`linkageList.${index}.linkageData`" :rules="rules.linkageData">
              <component :is="tag(item)" :parentData="getParentData(item)" v-model="item.linkageData" @change="valueChange" ref="comp"></component>
            </el-form-item>
            <span class="closeBtn" @click="delBtn(index)"><i class="el-icon-close"></i></span>
          </div>
        </el-form>
        <div class="addBtn">
          <el-link type="primary" :underline="false" @click="addClick">
            <i class="el-icon-circle-plus-outline"></i>
            添加联动
          </el-link>
        </div>
      </div>
      <div v-else class="emptyText">只有输入和下拉，且存在"上级字段"才能配置联动</div>
    </div>
    <div class="btnBox">
      <div class="btn" @click="runClick">执行联动</div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState, mapMutations } from 'vuex'
import SelectSelect from './component/selectSelect'
import SelectInput from './component/selectInput'
import InputSelect from './component/inputSelect'
import InputInput from './component/inputInput'
import { upperCase } from '@/utils'
export default {
  name: 'linkageConfig',
  components: {
    SelectSelect,
    SelectInput,
    InputSelect,
    InputInput
  },
  data() {
    return {
      formData: {
        linkageList: []
      },
      rules: {
        parentId: [{ required: true, message: '请选择上级字段', trigger: 'change' }],
        linkageData: [{ required: true, message: '', trigger: 'change' }]
      }
    }
  },
  watch: {
    'activeFormData.linkageList': {
      handler(val) {
        if (!val) return
        this.formData.linkageList = JSON.parse(JSON.stringify(val))
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    ...mapState('pageData', ['formDataList', 'activeFormData']),
    ...mapGetters('pageData', ['activeId']),
    parentFieldList() {
      let arr = []
      try {
        this.formDataList.forEach(item => {
          if (item.formId !== this.activeId) {
            arr.push(item)
          } else {
            throw new Error()
          }
        })
      } catch (error) {}

      // 过滤出类型为input和select
      return arr.filter(item => item.type === 'input' || item.type === 'select')
    },
    activeIdIndex() {
      return this.formDataList.findIndex(item => item.formId === this.activeId)
    },
    isShow() {
      return (this.activeFormData?.type === 'input' || this.activeFormData?.type === 'select') && this.parentFieldList?.length > 0 && this.activeIdIndex !== 0
    }
  },
  methods: {
    ...mapMutations('pageData', ['SETPROP']),
    linkageListInit() {
      return {
        parentId: '',
        linkageData: {}
      }
    },
    addClick() {
      this.formData?.linkageList?.push(this.linkageListInit())
    },
    delBtn(index) {
      this.formData.linkageList.splice(index, 1)
    },
    tag(item) {
      const parentData = this.formDataList.find(f => f.formId === item.parentId)
      const parentType = parentData?.type
      const currentType = this.activeFormData?.type
      // return item.parentId === '' || item?.parentId?.length === 0 ? null : upperCase(currentType) + upperCase(parentType)
      return currentType && parentType ? upperCase(currentType) + upperCase(parentType) : null
    },
    getParentData(item) {
      return this.formDataList.find(f => f.formId === item.parentId)
    },
    valueChange() {
      // this.SETPROP({
      //   key: 'linkageList',
      //   value: this.formData.linkageList
      // })
    },
    // 当前form校验
    verfiyForm() {
      return new Promise(resolve => {
        this.$refs?.formData?.validate(valid => {
          if (valid) {
            resolve('success')
            // this.SETPROP({
            //   key: 'linkageList',
            //   value: this.formData.linkageList
            // })
          }
        })
      })
    },
    runClick() {
      const fnList = this.$refs.comp?.map(item => {
        return item.verfiyForm()
      })
      if (!fnList) return
      Promise.all([...fnList, this.verfiyForm()]).then(res => {
        // console.log(this.formData.linkageList, '===res==')
        const pass = res.every(item => item === 'success')
        // 数据联动的所有数据
        if (pass) {
          this.SETPROP({
            key: 'linkageList',
            value: this.formData.linkageList
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.linkageConfig {
  padding-right: 10px;
  .linkage {
    margin-bottom: 66px;
  }
  .contentBox {
    padding: 12px 6px;
    background: #f8f8f8;
    position: relative;
    border-radius: 4px;
    margin-bottom: 10px;
    .closeBtn {
      position: absolute;
      right: -6px;
      top: -6px;
      display: block;
      width: 16px;
      height: 16px;
      line-height: 16px;
      background: rgba(0, 0, 0, 0.2);
      border-radius: 50%;
      color: #fff;
      text-align: center;
      z-index: 1;
      cursor: pointer;
      font-size: 12px;
      &:hover {
        background: red;
      }
    }
  }
  .emptyText {
    text-align: center;
    font-size: 14px;
    color: #e0e0e0;
    line-height: 200px;
  }
  .btnBox {
    position: fixed;
    height: 46px;
    border-top: solid 1px #eee;
    background: #fff;
    bottom: 0;
    right: 0;
    display: flex;
    flex-direction: row-reverse;
    width: 350px;
    z-index: 99;
    box-shadow: 0px -6px 6px 0px rgba(227, 227, 227, 0.5);
    .btn {
      line-height: 46px;
      padding: 0 10px;
      font-size: 14px;
      background: #1890ff;
      color: #fff;
      cursor: pointer;
      &:hover {
        opacity: 0.8;
      }
      &:active {
        opacity: 0.6;
      }
    }
  }
}
</style>